package com.virtium.vpm.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.virtium.vpm.dao.DAOFactory;
import com.virtium.vpm.hibernate.model.User;
import com.virtium.vpm.util.SecurityUtil;
import com.virtium.vpm.dao.UserDAO;



public class UserSessionManager {
	
    protected Logger log = Logger.getLogger(this.getClass());

    /**
     * Authenticate user against database. <p>
     * If login is successful, a login trail is added in LOGIN_TRAIL table.<p>
     * The system will verify the number of times that the user has tried to login.<p>
     * If this time exceeds the value indicated in the properties file, system will
     * lock this user's account.<p>
     * 
     * @see constants.properties NUM_LOGIN_TRIES for the number of login trials before locking the account.
     * @param username User's login name
     * @param password  User's password
     * @param dealershipId Value is not null for a trainee user
     * @param flag If flag is true, system is authenticating a trainee, else
     * if false, system is authenticating a non-trainee user.
     * @return If user exists, returns <code>UserSession object</code>.<br>
     * Else returns null.
     */
    public UserSession authenticateUser(String username, String password,
    		HttpSession session,HttpServletRequest request) 
    throws Exception {   	
    	User user = null;
    	UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
    	List ls = userDAO.findByUserName(username);
    	if(ls != null && ls.size() > 0)
    		user = (User)ls.get(0);        
        if (user == null) { // not authorized
            return null;
        }
        
        // wrong password
        if (!SecurityUtil.isValidPassword(user.getPassword(), password)) {
        } 
       
        userDAO.closeSession();
        userDAO = null;
        
        return populateUserSession(user, session);	
    }    
    
    /**
     * Populates user session object.
     * - usually called when user logs in successfully
     * 
     * @param user user object of logged in user
     * @param session session object to attached the user to
     * @return UserSession
     * @throws UserNotFoundException
     * @throws RecordNotFoundException 
     */
    private UserSession populateUserSession(User user, HttpSession session) 
    throws Exception {
    	if(user == null) return null;
        UserSession userSession = new UserSession(); 
        log.debug("Populating the user session object.");
        userSession.setUsername(user.getUserName());        
        userSession.setFullName(user.getFullName());        
        userSession.setSessionId(session.getId());
        userSession.setUser(user);
        userSession.setAdmin(user.getUserName().equals("admin"));	
        return userSession;
    }

}